
var key = "tk1678";
var base_url = "http://www.abbreviations.com/services/v1/defs.aspx";
var word = "";

var def_title_beg = "<h4 class=\"page_title\">";
var def_title_end = "</h4>";
var def_div = "<div class=\"hr dotted clearfix\">&nbsp;</div>";
var def_beg = "<p>";
var def_end = "</p>";
var page_content = "";

function render(result) {
	page_content = "";
	var r = result.getElementsByTagName("result");
	if(r.length == 0)
	{
		page_content = def_title_beg + "No results" + def_title_end;
		page_content += def_div;
		page_content += def_beg + "No results" + def_end;
	}
	else
	{
		for(i=0; i < r.length; i++)
		{
			page_content += def_title_beg + r[i].getElementsByTagName("term")[0].childNodes[0].nodeValue + def_title_end;
			page_content += def_div;
			page_content += def_beg + r[i].getElementsByTagName("definition")[0].childNodes[0].nodeValue + def_end;
		}
	}

	document.getElementById("content").innerHTML=page_content;
}

function onUserSearch()
{
	uw = document.getElementsByName("userword")[0].value;
	if(uw != null && uw != "")
	{
		word = trim(uw);
		getDefinition();
	}
}

var df_icon = "<img src='icons/DefinePlugIcon19.png' style='margin-bottom:0px'>";
function displayAbout()
{
	page_content = def_title_beg + "DefinePlug" + def_title_end;
	page_content += def_div;
	page_content += def_beg + "A tool to help you <u>quickly find the meaning</u> of a word or phrase." + def_end;
	page_content += def_beg + "How often have you come across a word or phrase that you don't understand? And how often have you just ignored it? Now it is very easy to find out its meaning with just one click." + def_end;
	page_content += def_beg + "Just select the word/phrase and click the " + df_icon + " button again. The meaning will be displayed right here, in this little popup. No need to open a new tab or window!" + def_end;
	page_content += def_div;
	page_content += def_title_beg + "Or, enter a word <input type='text' id='df_user_input' name='userword'> and click <input class='default' type='button' id='df_button' value='here' onclick='onUserSearch()'/>." + def_title_end;
	document.getElementById("content").innerHTML=page_content;
	document.getElementById("df_user_input").focus();
}

function getSelectedWord() {
	// Send a request to fetch data from Twitter's API to the background page.
	// Specify that onText should be called with the result.
	//chrome.extension.sendRequest({'action' : 'getSelectedWord'}, onGotSelection);

	chrome.tabs.getSelected(null, function(tab) {
			chrome.tabs.sendRequest(tab.id, {'action' : 'getSelectedWord'}, onGotSelection);
			});

}

function onGotSelection(selection) {
	if(selection != null && selection != "")
	{
		//word = selection;
		word = trim(selection);
		getDefinition();
	}
	else
	{
		displayAbout();
	}
}

//
// Normalize the term - e.g. change from plural to singular form. Often normalized forms have definitions but other fancy forms don't
//
// TODO: normalize past tenses, adverbs, adjectives etc.
// TODO: study some "stemming" algorithms
//
function normalizeTerm(term) {
	t = term.toLowerCase();
	l = t.length;
	//plurals ending with 'es'
	if(t.substr(l-2, 2) == "es") {
		return t.substr(0, l-2);
	}
	//plurals ending with 's'
	else if (t.substr(l-1, 1) == "s") {
		return t.substr(0, l-1);
	}
	/*
	//past tense forms ending with 'ed', e.g. disappeared ---> disappear
	else if (t.substr(l-2, 2) == "ed") {
		return t.substr(0, l-2);
	}
	//past tense forms ending with 'd', e.g. damaged ---> damage
	else if (t.substr(l-1, 1) == "d") {
		return t.substr(0, l-1);
	}
	*/
	else {
		return t;
	}
}

function tryNormalized() {
	var normalized_word = normalizeTerm(word);
	var url = base_url + "?tokenid=" + key + "&word=" + normalized_word;
	var xmlReq = new XMLHttpRequest();
	xmlReq.onreadystatechange=function()
	{
		if (xmlReq.readyState==4 && xmlReq.status==200)
		{
			var result2=xmlReq.responseXML;

			var r = result2.getElementsByTagName("result");
			if(r.length == 0)
			{
				page_content = def_title_beg + "No results" + def_title_end;
				page_content += def_div;
				page_content += def_beg + "Sorry, I could not find definition for this term. <a target='_blank' href='http://www.google.com/search?q=" + word + "'>Click here to search on Google.</a>" + def_end;
				document.getElementById("content").innerHTML=page_content;
			} else {
				render(result2);
			}
		}
	}

	xmlReq.open("GET", url, true);
	xmlReq.send();
}

function processResponse(xmlResponse) {
	var r = xmlResponse.getElementsByTagName("result");
	if(r.length == 0)
	{
		tryNormalized();
	} else {
		render(xmlResponse);
	}
}

function getDefinition() {
	var url = base_url + "?tokenid=" + key + "&word=" + word;
	var xmlReq = new XMLHttpRequest();
	xmlReq.onreadystatechange=function()
	{
		if (xmlReq.readyState==4 && xmlReq.status==200)
		{
			var xmlDoc=xmlReq.responseXML;
			processResponse(xmlDoc);
		}
	}

	xmlReq.open("GET", url, true);
	xmlReq.send();
}

function fetchDefinition() {
	chrome.tabs.getSelected(null, function (tab) {
				if(tab.url.substring(0,9) == "chrome://") {
					displayAbout();
				} else {
					getSelectedWord();
				}
			});
}

